package com.cskaoyan.typeHandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import javax.lang.model.element.VariableElement;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2021/4/9 - 11:03
 */

@MappedTypes(Integer[].class) // 映射的java类型
@MappedJdbcTypes(JdbcType.VARCHAR) // 映射的数据库类型
public class IntegerArrayTypeHandler extends BaseTypeHandler<Integer[]> {

    ObjectMapper objectMapper = new ObjectMapper();

    @SneakyThrows
    @Override
    // 输入映射的方法
    public void setNonNullParameter(PreparedStatement preparedStatement, int index, Integer[] integers, JdbcType jdbcType) throws SQLException {

        //integer[] 👉 string
        String values = objectMapper.writeValueAsString(integers);
        preparedStatement.setString(index,values);
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, int columIndex) throws SQLException {
        String result = resultSet.getString(columIndex);
        return transfer(result);
    }

    @Override
    public Integer[] getNullableResult(CallableStatement callableStatement, int columIndex) throws SQLException {
        String result = callableStatement.getString(columIndex);
        return transfer(result);
    }

    private Integer[] transfer(String result){

        if(result != null && !"".equals(result)){
            return new Integer[0];
        }
        Integer[] integers = new Integer[0];
        try {
            integers = objectMapper.readValue(result,Integer[].class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return integers;

    }
}
